// config
window.APP = { version : 'v='+v };
angular.module('app')
.config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide',function ($controllerProvider,   $compileProvider,   $filterProvider,   $provide) {
            // lazy controller, directive and service
            app.controller = $controllerProvider.register;
            app.directive  = $compileProvider.directive;
            app.filter     = $filterProvider.register;
            app.factory    = $provide.factory;
            app.service    = $provide.service;
            app.constant   = $provide.constant;
            app.value      = $provide.value;
        }])
.config(function($provide){
    jQuery.validator.addMethod("mail", function (value, element) {
        var mail = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/;
        return this.optional(element) || (mail.test(value));
    }, "邮箱格式不对");

        //电话和手机验证规则
        jQuery.validator.addMethod("contacts", function (value, element) {
            var contacts = /^0\d{2,3}-\d{7,8}$/;
            var mobile = /^1[3|4|5|7|8]\d{9}$/;
            var noactel = /^\d{7,8}$/;
            return function(){
                if(contacts.test(value)||mobile.test(value)||noactel.test(value))
                    return true
            }();
        }, "电话格式如：0371-68787027");

        //电话验证规则
        jQuery.validator.addMethod("phone", function (value, element) {
            var phone = /^0\d{2,3}-\d{7,8}$/;
            return this.optional(element) || (phone.test(value));
        }, "电话格式如：0371-68787027");

        //区号验证规则  
        jQuery.validator.addMethod("ac", function (value, element) {
            var ac = /^0\d{2,3}$/;
            return this.optional(element) || (ac.test(value));
        }, "区号如：010或0371");

        //无区号电话验证规则  
        jQuery.validator.addMethod("noactel", function (value, element) {
            var noactel = /^\d{7,8}$/;
            return this.optional(element) || (noactel.test(value));
        }, "电话格式如：68787027");

        //手机验证规则  
        jQuery.validator.addMethod("mobile", function (value, element) {
            var mobile = /^1[3|4|5|7|8]\d{9}$/;
            return this.optional(element) || (mobile.test(value));
        }, "手机格式不对");

        //邮箱或手机验证规则  
        jQuery.validator.addMethod("mm", function (value, element) {
            var mm = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$|^1[3|4|5|7|8]\d{9}$/;
            return this.optional(element) || (mm.test(value));
        }, "格式不对");

        //url  
        jQuery.validator.addMethod("url", function (value, element) {
            var url=/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
            return this.optional(element) || (url.test(value));
        }, "格式不对");

        //电话或手机验证规则  
        jQuery.validator.addMethod("tm", function (value, element) {
            var tm=/(^1[3|4|5|7|8]\d{9}$)|(^\d{3,4}-\d{7,8}$)|(^\d{7,8}$)|(^\d{3,4}-\d{7,8}-\d{1,4}$)|(^\d{7,8}-\d{1,4}$)/;
            return this.optional(element) || (tm.test(value));
        }, "格式不对");

        //年龄
        jQuery.validator.addMethod("age", function(value, element) {   
            var age = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/;
            return this.optional(element) || (age.test(value));
        }, "不能超过120岁"); 
        ///// 20-60   /^([2-5]\d)|60$/

        //传真
        jQuery.validator.addMethod("fax",function(value,element){
            var fax = /^(\d{3,4})?[-]?\d{7,8}$/;
            return this.optional(element) || (fax.test(value));
        },"传真格式如：0371-68787027");

        //验证当前值和目标val的值相等 相等返回为 false
        jQuery.validator.addMethod("equalTo2",function(value, element){
            var returnVal = true;
            var id = $(element).attr("data-rule-equalto2");
            var targetVal = $(id).val();
            if(value === targetVal){
                returnVal = false;
            }
            return returnVal;
        },"不能和原始密码相同");

        //大于指定数
        jQuery.validator.addMethod("gt",function(value, element){
            var returnVal = false;
            var gt = $(element).data("gt");
            if(value > gt && value != ""){
                returnVal = true;
            }
            return returnVal;
        },"不能小于0 或空");

        //汉字
        jQuery.validator.addMethod("chinese", function (value, element) {
            var chinese = /^[\u4E00-\u9FFF]+$/;
            return this.optional(element) || (chinese.test(value));
        }, "格式不对");

        //指定数字的整数倍
        jQuery.validator.addMethod("times", function (value, element) {
            var returnVal = true;
            var base=$(element).attr('data-rule-times');
            if(value%base!=0){
                returnVal=false;
            }
            return returnVal;
        }, "必须是发布赏金的整数倍");

        //身份证
        jQuery.validator.addMethod("idCard", function (value, element) {
            var isIDCard1=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;//(15位)
            var isIDCard2=/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;//(18位)

            return this.optional(element) || (isIDCard1.test(value)) || (isIDCard2.test(value));
        }, "格式不对");

        $.extend({'cookie':function(name, value, options) {
            if(cookieIsEnable){
                if (typeof value != 'undefined') { // name and value given, set cookie
                    options = options || {};
                    if (value === null) {
                        value = '';
                        options.expires = -1;
                    }
                    var expires = '';
                    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                        var date;
                        if (typeof options.expires == 'number') {
                            date = new Date();
                            date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                        } else {
                            date = options.expires;
                        }
                        expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                    }
                    var path = options.path ? '; path=' + options.path : '';
                    var domain = options.domain ? '; domain=' + options.domain : '';
                    var secure = options.secure ? '; secure' : '';
                    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
                } else { // only name given, get cookie
                    var cookieValue = null;
                    if (document.cookie && document.cookie != '') {
                        var cookies = document.cookie.split(';');
                        for (var i = 0; i < cookies.length; i++) {
                            var cookie = jQuery.trim(cookies[i]);
                            // Does this cookie string begin with the name we want?
                            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                break;
                            }
                        }
                    }
                    return cookieValue;
                }
            }else{
                alert('cookie 禁用');
            }
            function cookieIsEnable(){
                return window.navigator.cookieEnabled;
            }
        }});
        jQuery.validator.addMethod('stringCheck',function(value,element){
            return this.optional(element)||/^[a-zA-Z0-9\u4e00-\u9fa5]*$/.test(value);
        },'只能包含字母、数字和汉字');
        jQuery.validator.addMethod('isPhone',function(value,element){
            var mobileRgx = /^1[3-8][0-9]\d{8}$/;
            var telRgx =  /^(\d{3,4}-){0,1}\d{7,9}$/;
            return this.optional(element)||mobileRgx.test(value)||telRgx.test(value);
        },'请输入正确格式的手机或电话号码');
        jQuery.validator.addMethod('maxLengthB',function(value,element,params){
            var b=0,l=value.length;
            for(var i=0;i<l;i++){
                if(value.charCodeAt(i)>255){
                    b+=2;
                }else{
                    b++;
                }
            }
            return this.optional(element)||b<=params[0];
        });
    })
.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
      // We configure ocLazyLoad to use the lib script.js as the async loader
      $ocLazyLoadProvider.config({
          debug:false,
          events: true,
          modules: [{
              name: 'toaster',
              files: [
              'lib/angular/toaster.js',
              'lib/angular/toaster.css'
              ]
          }]
      });
  }])
    .filter('label', function() { // 显示为标签
      return function(input, s) {
          var l = input.split(s);
          var r = '';
          for(var i=0; i<l.length; i++) {
              r += '<label class="label label-info">' + l[i] + '</label>\n';
          }
          return r;
      }
  })
    .filter('trustHtml', function ($sce) { // 安全HTML
        return function (input) {
            return $sce.trustAsHtml(input);
        }
    })
    .service("ajaxRquest",["$q","$http",function($q,$http){
        var PD=new Array ;
        var PD2=new Array ;
        Array.prototype.remove=function(val){
            var index=this.indexOf(val);
            if(index>-1){
                this.splice(index,1);
            }
        }
        var request_param = function () {
            var clientName = 'nuojfApp';
            var clientVersion = '1.0.0';
            var os = 'ios';
            var osVersion = '7.0';
            var brand = 'Xiaomi';
            var model = 'RedmiNote4';
            var uuid = 'abcdefg';
            var networkType = 'wifi';
            var resolution = '1920*1080';
            var st = new Date().getTime();
            var key = 'key=72q*ngZst6BoNMcUq%KvRUBdTnrw*DZ$';
            var paramStr = key+'&brand='+brand+'&clientName='+clientName+'&clientVersion='+clientVersion+'&model='+model+'&networkType='+networkType+'&os='+os+'&osVersion='+osVersion+'&resolution='+resolution+'&st='+st+'&uuid='+uuid;
            var sign = hex_md5(paramStr);
            return '?clientName='+clientName + '&clientVersion='+clientVersion+ '&os='+os+ '&osVersion='+osVersion+ '&brand='+brand+ '&model='+model+'&uuid='+uuid+ '&networkType='+networkType+ '&resolution='+resolution+ '&st='+st+ '&sign='+sign;
        };
       function loadingMessage(str) {
            var html = '<div class="loadingMessage" style="position: fixed; text-align: center; width: 100%; display:none; z-index:1000;"><font style="background-color: rgba(0, 0, 0, 0.7); border-radius: 5px; color: #fff; z-index:1000; display:inline-block; line-height: 170%; max-width: 80%; padding: 5px 10px;font-size:14px">'+ str +'</font></div>';
            $("body").append(html);
            $("body .loadingMessage").fadeIn("normal");
        }
        function hideLoading(){
            $("body .loadingMessage").fadeOut("normal",function(){
                $(this).remove();
            })
        }
        this.getData=function(url,params,method){
            var dtd = $.Deferred(); // 新建一个Deferred对象
            var dtd2=$.Deferred();
            for(var i=0;i<PD.length;i++){
                if(PD[i]==url){
                    return dtd2.promise();
                }
            }
            PD.push(url);
            PD2.push(params);
            var ifcToken= $.cookie('ifcToken');
            if(url !== "/funScenes/recommendactivity"){
                url = "/iFengChao-Hui-Web"+url+request_param();
            }else{
                url = "/iFengChao-Run-Web"+url+request_param();
            }
            if(method==undefined||method==""||method=="undefined"){
                var method='POST';
            }
            var  secret='8$T6acbOjB46nHoy&*dBaWS^YPUsMDJj';
            params=JSON.stringify(params);
            var requestStr=DES3.encrypt(secret,params);
            function ajax(){
                hideLoading();
                loadingMessage("数据加载中...")
                // var dtd = $.Deferred(); // 新建一个Deferred对象
                $.ajax({
                    url : url,
                    type:method,
                    data: {'data':requestStr},
                }).then(function(result) {
                    hideLoading();
                    if(result){
                        var decResult = DES3.decrypt(secret,result);
                        var msg = JSON.parse(decResult);
                        msg = JSON.parse(decResult);
                        dtd.resolve(msg);
                    }
                    PD=[];
                    PD2=[]
                },function(result){
                    hideLoading();
                    if(result){
                        var decResult = DES3.decrypt(secret,result);
                        msg = JSON.parse(decResult);
                        dtd.reject(msg);
                    }
                    PD=[];
                    PD2=[]
                });
                return dtd.promise();
            }
            return $.when(ajax());
        };
    }])
.service("ajaxRquestImg",["$q","$http",function($q,$http){
    var request_param = function () {
        var clientName = 'nuojfApp';
        var clientVersion = '1.0.0';
        var os = 'ios';
        var osVersion = '7.0';
        var brand = 'Xiaomi';
        var model = 'RedmiNote4';
        var uuid = 'abcdefg';
        var networkType = 'wifi';
        var resolution = '1920*1080';
        var st = new Date().getTime();
        var key = 'key=82q*ngZzt7BoMMcUq%NvEUBdTnrw*DZ$';
        var paramStr = key+'&brand='+brand+'&clientName='+clientName+'&clientVersion='+clientVersion+'&model='+model+'&networkType='+networkType+'&os='+os+'&osVersion='+osVersion+'&resolution='+resolution+'&st='+st+'&uuid='+uuid;
        var sign = hex_md5(paramStr);
        return '?clientName='+clientName + '&clientVersion='+clientVersion+ '&os='+os+ '&osVersion='+osVersion+ '&brand='+brand+ '&model='+model+'&uuid='+uuid+ '&networkType='+networkType+ '&resolution='+resolution+ '&st='+st+ '&sign='+sign;
    };

     function loadingMessage(str) {
            var html = '<div class="loadingMessage" style="position: fixed; text-align: center; width: 100%; display:none; z-index:100000;"><font style="background-color: rgba(0, 0, 0, 0.7); border-radius: 5px; color: #fff; z-index:1000; display:inline-block; line-height: 170%; max-width: 80%; padding: 5px 10px;font-size:14px">'+ str +'</font></div>';
            $("body").append(html);
            $("body .loadingMessage").fadeIn("normal");
        }
    function hideLoading(){
        $("body .loadingMessage").fadeOut("normal",function(){
            $(this).remove();
        })
    }

    this.getData=function(url,params,method){
        var ifcToken= $.cookie('ifcToken');
        url = "/iFengChao-Hui-Web"+url+request_param();
        if(method==undefined||method==""||method=="undefined"){
            var method='POST';
        }
        var  secret='8$T6acbOjB46nHoy&*dBaWS^YPUsMDJj';
        function ajax(){
                var dtd = $.Deferred(); // 新建一个Deferred对象
                loadingMessage("图片上传中...");
                $.ajax({
                    url : url,
                    data: params
                }).then(function(result) {
                    // console.log(result);
                    hideLoading();
                    var decResult = DES3.decrypt(secret,result);
                    var msg = JSON.parse(decResult);
                    msg = JSON.parse(decResult);
                    dtd.resolve(msg);
                },function(result){
                    hideLoading();
                    var decResult = DES3.decrypt(secret,result);
                    msg = JSON.parse(decResult);
                    dtd.reject(msg);
                });
                return dtd.promise();
            }
            return $.when(ajax());
        };
    }])
.directive("pagination",function(){
    return {
        restrict:"E",
        replace:true,
        transclude:true,
        scope:{
            conf:"=",
        },
        link:function(scope,element,attrs){
            var button1=element.find(".button1")
            var button2=element.find(".button2")
            scope.jugedisable=function(){
                if(scope.conf.currentPage<=1){
                    scope.conf.currentPage=1;
                    button1.attr("disabled",true);
                    button1.css('background',"#eee")
                }else{
                    
                    button1.removeAttr("disabled");
                    button1.css('background',"#fff")
                }

                if(scope.conf.currentPage>=scope.totalPageNum){
                    scope.conf.currentPage=scope.totalPageNum;
                    button2.attr("disabled",true);
                    button2.css('background',"#eee")
                }else{
                    button2.removeAttr("disabled");
                    button2.css('background',"#fff")
                }
            }
                // scope.jugedisable()
            },
            controller:function($scope){
                if(typeof $scope.conf.total=='string'){
                   $scope.conf.total=Number($scope.conf.total)
               }
               if(typeof $scope.conf.pageSize){
                $scope.conf.pageSize=Number($scope.conf.pageSize)
            }
            $scope.setList=function(){
                $scope.totalPageNum=Math.ceil($scope.conf.total/$scope.conf.pageSize)
                if($scope.totalPageNum<=1){
                    $scope.totalPageNum=1
                    $scope.isPaging=false
                }else{
                    $scope.isPaging=true
                }
                    //将接口请求到的分页总数放入数组记录
                    $scope.pageList=[];
                    
                    for(var i=1 ; i<=$scope.totalPageNum;i++){
                        $scope.pageList.push(i)
                    }
                    // if($scope.conf.paginLength>=$scope.totalPageNum){
                    //     $scope.conf.paginLength=$scope.totalPageNum
                    // }

                    //根据总页数和长度划分区间   每个区间为显示的分页数
                    
                    $scope.listRegion=[]
                    for(var i=1;i<=$scope.totalPageNum;i++){
                            // console.log(i,$scope.conf.paginLength)
                            if(i%$scope.conf.paginLength==1){
                                // alert(111)
                                $scope.listRegion.push(i);
                            }
                        }
                        // console.log($scope.listRegion)
                    }

            // $scope.setList()

            //判断是否到达下一个分页区间
            $scope.nextList=function(){
                for(var i=0;i<$scope.listRegion.length;i++){
                    if(i<$scope.listRegion.length-1){
                        if($scope.conf.currentPage>=$scope.listRegion[i]&&$scope.conf.currentPage<$scope.listRegion[i+1]){
                                $scope.startPageNum=$scope.listRegion[i];           //记录开始页码
                                $scope.endPageNum=$scope.startPageNum+$scope.conf.paginLength-1 //记录结束页码
                                $scope.newPageList= $scope.pageList.slice($scope.startPageNum-1,$scope.endPageNum)//在总的分页素组中截取分页区间，呈现在页面的分页都是在这个数组中
                                break;
                            }
                        }else{
                                $scope.startPageNum=$scope.listRegion[i];           //记录开始页码
                                $scope.newPageList= $scope.pageList.slice($scope.startPageNum-1,$scope.totalPageNum)
                                break;
                            }
                        }
                    }
                // $scope.nextList()

                // alert($scope.conf.totalPageNum)
                $scope.$watch("conf.total++conf.pageSize",function(newValue){
                    
                    $scope.setList()
                    $scope.nextList()
                    $scope.jugedisable()
                    $scope.isShowPoint()
                    if(typeof ($scope.conf.jumpPage)=="function"){
                        $scope.conf.jumpPage($scope.totalPageNum)
                    }
                })


                //点击...按钮跳转方法 
                $scope.passMore=function(){
                    $scope.conf.currentPage+=$scope.conf.paginLength
                }


                $scope.choosePage=function(num){
                    if(num!==undefined){
                      $scope.goTo=''
                      $scope.conf.currentPage=num
                      return false
                  }
                  if(Number($scope.goTo)>=Number($scope.totalPageNum)){
                    $scope.goTo=$scope.totalPageNum
                }
                $scope.conf.currentPage=Number($scope.goTo)

            }
            $scope.prevPage=function(){
                $scope.conf.currentPage-=1;
                $scope.goTo=''
            }

            $scope.nextPage=function(){
                $scope.conf.currentPage+=1;
                $scope.goTo=''
            }

            
            $scope.isShowPoint=function(){
                if($scope.conf.currentPage<$scope.listRegion[$scope.listRegion.length-1]){
                    $scope.isShow=true
                }else{
                    $scope.isShow=false
                }
            }

            $scope.$watch("conf.currentPage",function(){
                $scope.isShowPoint();
                $scope.nextList();
                $scope.jugedisable()
            })

            $scope.keyUpFn=function(e){
                if(e.keyCode==13){
                    $scope.choosePage()
                }
            }
        },
        template:'<div class="paging noselect " ng-show="isPaging"><div class="pagingContent">'+
        '<button ng-click="choosePage(1)" class="button1">首页</button>'+
        '<button ng-click="prevPage()" class="button1" >上一页</button>'+
        '<ul class="fl">'+
        '<li ng-repeat="item in newPageList"  ng-class="{current:conf.currentPage==item}" ng-click="choosePage(item)">{{item}}</li>'+
        '<li ng-show="isShow" ng-click="passMore()">...</li>'+
        '<li ng-show="isShow" ng-click="choosePage(totalPageNum)">{{totalPageNum}}</li>'+
        '</ul>'+
        '<button ng-click="nextPage()" class="button2">下一页</button>'+
        '<button ng-click="choosePage(totalPageNum)" class="button2">尾页</button>'+
        '<span>{{conf.currentPage}}/共{{totalPageNum}}页</i></span>'+
        '<i class="fl jump">跳转到第</i><input type="text" value="1"  ng-keyup="keyUpFn($event)" ng-model="goTo"><i class="fl jump">页</i>'+
        '<button ng-click="choosePage()">GO</button>'+
        '</div></div>'
    }
})
.factory('excel',function($window){
    var uri='data:application/vnd.ms-excel;base64,',
    template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
    template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
    base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
    format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
    return {
        tableToExcel:function(tableId,worksheetName,deleteObj){
            setTimeout(function(){
                if (!tableId.nodeType) table = $(document.getElementById(tableId)).clone()[0]
                    if(deleteObj){
                        var len; 
                        for(var i=0;i<deleteObj.length;i++){
                         len = table.rows.length; 
                         for(var j = 0;j < len;j++){
                           var k=deleteObj[i]-i
                           table.rows[j].deleteCell(k);
                       }
                   }
               }   
               var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
               document.getElementById(tableId+"a").href = uri + base64(format(template, ctx));
               document.getElementById(tableId+"a").download = worksheetName+'.xls';
               document.getElementById(tableId+"a").click();
           },100)
        }
    };
})
.directive('lazyLoad',function(){
    return{
       restrict: 'E',
       scope:{
           data:'='
       },
       replace: true,
       template:"<div><span class='noMoreData' ng-show='noMoreData'>没有更多数据了</span></div>",
       link:function(scope,element,attrs,ctrls){
             // element.parent('.scroll-wrap').css({
             //    'position':'absolute',
             //    'bottom':0,
             //    'top':0,
             //    'width':'100%',
             //    'left':0,
             //    'marginTop':'1rem'
             // })
             var datHeight;
             var flag=true,flag2=true;
             var transform=getTransform();
             scope.onOff=false
             scope.element=element.siblings('.scroll-body')[0]
             scope.getStyle=function(property){
              return document.defaultView.getComputedStyle?document.defaultView.getComputedStyle(scope.element,false)[property]:scope.element.currentStyle[property];
          }
          scope.getPosition=function(){
            var pos={x:0,y:0};
            if(transform){
                var transformValue=scope.getStyle(transform);
                if(transformValue=='none'){
                    scope.element.style[transform]='translate3d(0, 0, 0)';
                    return pos
                }else{
                    var temp=transformValue.match(/-?\d+/g);
                    return pos={
                        x:parseInt(temp[4].trim()),
                        y:parseInt(temp[5].trim())
                    }
                }
            }else{
              if(scope.getStyle('position')=='static'){
                 scope.element.style.position='relative';
             }else{
                var x=parseInt(scope.getStyle('left')?scope.getStyle('left'):0);
                var y=parseInt(scope.getStyle('top')?scope.getStyle('top'):0)
                return pos={
                   x:x,
                   y:y
               }
           }
       }
   }
   scope.setPosition=function(pos){
       if(transform){
        scope.element.style[transform]='translate3d(0,'+pos.y+'px,0)'
    }else{
                    // scope.element.style.left=pos.x+'px';
                    scope.element.style.top=pos.y+'px'
                }
                 // return elem
             }

             scope.setDrag=function(){
                scope.element.addEventListener("touchstart",start,{passive:false});
                function start(event){
                    clearInterval(scope.timer);
                    scope.datHeight=element.siblings('.scroll-body').height()-element.parent('.scroll-wrap').height()
                    
                    scope.startX=event.targetTouches[0].pageX;
                    scope.startY=event.targetTouches[0].pageY;
                    var pos=scope.getPosition();
                    scope.sourceX=pos.x;
                    scope.sourceY=pos.y;
                    scope.oldY=0
                    scope.element.addEventListener("touchmove",move,{passive:false});
                    scope.element.addEventListener("touchend",end,{passive:false});
                    return false
                    
                }
                function move(event){
                  event.preventDefault()
                  
                  var currentX=event.targetTouches[0].pageX,
                  currentY=event.targetTouches[0].pageY,
                  distanceX=currentX-scope.startX,
                  distanceY=currentY-scope.startY;
                  scope.scrollTop=scope.sourceY+distanceY
                  if(scope.datHeight<0&&distanceY<0){
                    return false
                }
                if(scope.scrollTop>0){
                    scope.scrollTop*=0.4
                    scope.onOff=true
                }else{
                    scope.onOff=false
                }
                if(scope.scrollTop>100){
                    scope.scrollTop=100
                }
                if(scope.scrollTop<(-scope.datHeight)&&scope.datHeight>0){
                   scope.$apply(function(){
                     if(flag){
                       clearTimeout(scope.timer3)
                       flag=false
                       if(Math.ceil(scope.data.total/scope.data.pageSige)>scope.data.currentPage){
                        scope.data.currentPage++;
                    }else{
                        flag2=false
                        loadingMessage('没有更多数据了')
                        setTimeout(function(){hideLoading(); flag2=true},1000)
                    }
                    scope.timer3=setTimeout(function(){flag=true},800)
                }
            })
               }
               if(scope.scrollTop<(-scope.datHeight)&&scope.datHeight>0){
                scope.scrollTop=-scope.datHeight
            }


            scope.setPosition({
                x:0,
                y:scope.scrollTop.toFixed()
            })
            scope.speedy=scope.sourceY+distanceY-scope.oldY;
            scope.oldY=scope.sourceY+distanceY
            return false

        }
        function end(event){
                      // event.preventDefault()
                      if(scope.onOff){
                       if(scope.scrollTop>0){
                        scope.startMove(0,300 ,'easeOut',function(){
                            if(scope.scrollTop>80){
                             scope.$apply(function(){
                                scope.data.currentPage=0
                            }) 
                         }
                         
                     }) 
                    }
                }else{
                    scope.move()
                }
                
                document.removeEventListener('touchmove',move,{passive:false});
                document.removeEventListener('touchend',end)
                return false

            }
        }

        function getTransform(){
            var transform='',
            divStyle=document.createElement('div').style,
            transformArr=['transform','webkitTransform','MozTransform','msTransform','oTransform'],
            i=0,
            len=transformArr.length;
            for( ;i<len;i++ ){
                if(transformArr[i] in divStyle)
                    return transform=transformArr[i];
            }
            return transform
        }
        function loadingMessage(str) {
            var html = '<div class="loadingMessage" style="position: fixed; text-align: center; width: 100%; display:none; z-index:1000;"><font style="background-color: rgba(0, 0, 0, 0.7); border-radius: 5px; color: #fff; z-index:1000; display:inline-block; line-height: 170%; max-width: 80%; padding: 5px 10px;font-size:14px">'+ str +'</font></div>';
            $("body").append(html);
            $("body .loadingMessage").fadeIn("normal");
        }

        function hideLoading(){
            $("body .loadingMessage").fadeOut("normal",function(){
                $(this).remove();
            })
        }
        scope.setDrag()

        scope.move=function(){
         clearInterval(scope.timer);
         scope.timer=setInterval(function(){
            scope.speedy*=0.9522;
            if(transform){
                
                var transformValue=scope.getStyle(transform);
                
                var temp=transformValue.match(/-?\d+/g);
                if(temp){
                   var pos=scope.getPosition();
               }else{
                clearInterval(scope.timer);
                return false;
            }
        }
        
        scope.y=pos.y+scope.speedy;

        if(scope.y<-scope.datHeight){
          scope.y=-scope.datHeight;
          scope.speedy*=-0.05;
      }else if(scope.y>0){
          scope.y=0;
          scope.speedy*=-0.05;
      }

      if(Math.abs(scope.speedy)<1){
          scope.speedy=0;
      }
      if(scope.speedy==0){
       clearInterval(scope.timer);
   }else{
       scope.setPosition({
        x:0,
        y:scope.y.toFixed()
    })
   }
},15)   
     }   

     scope.startMove=function(target,times,fx,fn){
        var pos=scope.getPosition()
        
        var startTime = now();
        
        clearInterval(scope.timer2);
        
        scope.timer2= setInterval(function(){
            
            var changeTime = now();
            
                    var t = times - Math.max(0,startTime - changeTime + times);  //0到2000
                    
                    
                    var value = Tween[fx](t,pos.y,target-pos.y,times);
                    

                    scope.setPosition({
                        x:0,
                        y:value.toFixed()
                    })
                    

                    
                    if(t == times){
                        clearInterval(scope.timer2);
                        fn&&fn()
                    }
                    
                },13);

        function now(){
            return (new Date()).getTime();
        }
    }
    var Tween = {
      
                easeOut: function(t, b, c, d){  //减速曲线
                    return -c *(t/=d)*(t-2) + b;
                }
            }


        }
    }
}).filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);
